package com.xinzhilibrary.service.impl;

import com.xinzhilibrary.dao.ICheckUserInfoDao;
import com.xinzhilibrary.dao.IGoodsInfoDao;
import com.xinzhilibrary.dao.InnerOrderDao;
import com.xinzhilibrary.model.GoodsInfo;
import com.xinzhilibrary.model.InnerOrderInfo;
import com.xinzhilibrary.model.OrderInfo;
import com.xinzhilibrary.model.Result;
import com.xinzhilibrary.service.InnerOrderService;
import com.xinzhilibrary.util.CheckJWT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Service
public class InnerOrderServiceImpl implements InnerOrderService {
    @Autowired
    private InnerOrderDao innerOrderDao;
    @Autowired
    private IGoodsInfoDao iGoodsInfoDao;
    @Autowired
    private ICheckUserInfoDao iCheckUserInfoDao;
    CheckJWT checkJWT = new CheckJWT();

    /**
     * 内购订单
     *
     * @param innerOrderInfo //内购订单信息
     * @param token //用户token
     * @return //返回结果
     */
    @Override
    @Transactional
    public Result insertInnerOrder(InnerOrderInfo innerOrderInfo, String token) {
        // 检查令牌是否无效
        if (isTokenInvalid(token)) {
            return Result.error("无效的令牌");
        }

        // 检查JWT令牌是否有效
        if (!checkJWT.checkJwt(token)) {
            return Result.error("当前身份验证失效");
        }

        try {
            // 插入内部订单信息
            if (insertInnerOrder(innerOrderInfo) <= 0) {
                throw new RuntimeException("新增失败");
            }
            // 返回成功结果
            return Result.success("新增进货单成功");
        } catch (Exception e) {
            // 打印异常堆栈信息
            e.printStackTrace();
            // 返回包含异常信息的错误结果
            return Result.error("系统错误：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result payForOrder(int igoStatus, String token) {
        // 检查令牌是否无效
        if (isTokenInvalid(token)) {
            return Result.error("无效的令牌");
        }

        // 检查JWT令牌是否有效
        if (!checkJWT.checkJwt(token)) {
            return Result.error("当前身份验证失效");
        }

        try {
            // 获取管理员余额
            double managerMoney = innerOrderDao.selectManagerMoney();
            // 获取订单商品总价值
            ArrayList<InnerOrderInfo> InnerOrderInfos = innerOrderDao.selectAllInnerOrderByStatus(igoStatus);
            if (!InnerOrderInfos.isEmpty()){
                double goodsValue = 0;
                for (InnerOrderInfo innerOrderInfo:InnerOrderInfos) {
                    goodsValue += innerOrderInfo.getIgoGoodsValue();
                }
                // 检查管理员余额是否足够
                if (managerMoney < goodsValue) {
                    return Result.error("管理员余额不足");
                }
                // 更新管理员余额
                if (updateManagerMoney(managerMoney - goodsValue) <= 0) {
                    throw new RuntimeException("管理员支付失败");
                }
                // 更新或插入商品信息
                if (!updateOrInsertGoods(InnerOrderInfos)) {
                    throw new RuntimeException("商品信息更新或新增失败");
                }
                // 返回成功结果
                return Result.success("管理员支付成功");
            }
        } catch (Exception e) {
            // 打印异常堆栈信息
            e.printStackTrace();
            // 返回包含异常信息的错误结果
            return Result.error("系统错误：" + e.getMessage());
        }
        return Result.error("系统错误");
    }
    /**
     * 检查令牌是否无效
     *
     * @param token 令牌字符串
     * @return 如果令牌为空或仅包含空格，则返回true，否则返回false
     */
    private boolean isTokenInvalid(String token) {
        return token == null || token.trim().isEmpty();
    }

    /**
     * 更新管理员余额
     * @param newManagerMoney 新的管理员余额
     * @return 更新操作影响的行数
     */
    private int updateManagerMoney(double newManagerMoney) {
        return innerOrderDao.updateManagerMoney(newManagerMoney);
    }

    /**
     * 插入内部订单信息
     * @param innerOrderInfo 内部订单信息对象
     * @return 插入操作影响的行数
     */
    private int insertInnerOrder(InnerOrderInfo innerOrderInfo) {
        return innerOrderDao.insertInnerOrder(innerOrderInfo);
    }

    /**
     * 更新或插入商品信息
     * @param InnerOrderInfos 内部订单信息对象
     * @return 如果操作成功则返回true，否则返回false
     */
    private boolean updateOrInsertGoods(ArrayList<InnerOrderInfo> InnerOrderInfos) {
        // 遍历集合并查询商品名称是否存在
        for (InnerOrderInfo innerOrderInfo:InnerOrderInfos) {
            String goodsName = innerOrderDao.selectGoodsByName(innerOrderInfo.getIgoGoodsName());
            if (goodsName == null) {
                // 商品不存在，创建新的商品信息并插入
                GoodsInfo goodsInfo = createGoodsInfo(innerOrderInfo);
                return iGoodsInfoDao.insertGoods(goodsInfo) > 0;
            } else {
                // 商品存在，更新商品信息
                int goodsNum = innerOrderInfo.getIgoGoodsNum();
                int newGoodsNum = goodsNum + innerOrderDao.selectGoodsNum(innerOrderInfo.getIgoGoodsName());//当前库存内的商品数量

                return iGoodsInfoDao.updateGoods(newGoodsNum, innerOrderInfo.getIgoGoodsName()) > 0;
            }
        }
        return false;
    }

    /**
     * 创建商品信息对象
     * @param innerOrderInfo 内部订单信息对象
     * @return 创建的商品信息对象
     */
    private GoodsInfo createGoodsInfo(InnerOrderInfo innerOrderInfo) {
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsId(innerOrderInfo.getGoodsId());
        goodsInfo.setGoodsName(innerOrderInfo.getIgoGoodsName());
        goodsInfo.setGoodsInventory(innerOrderInfo.getIgoGoodsNum());
        goodsInfo.setGoodsValue(innerOrderInfo.getGoodsValue());
        goodsInfo.setGoodsType(innerOrderInfo.getGoodsType());
        goodsInfo.setGoodsPhoto(innerOrderInfo.getGoodsPhoto());
        goodsInfo.setGoodsDescribe(innerOrderInfo.getGoodsDescribe());
        goodsInfo.setGoodsStatus(1);
        return goodsInfo;
    }

    @Override
    @Transactional
    public Result clearOrder(int orderGoodsUserId, String token) {//清空购物车
        if (isTokenInvalid(token)) {
            return Result.error("无效的令牌");
        }
        if (!checkJWT.checkJwt(token)) {
            return Result.error("当前身份验证失效");
        }
        try {
            //根据用户ID查看用户余额
            double money = iGoodsInfoDao.selectUserMoney(orderGoodsUserId);
            double goodsMoney = check(orderGoodsUserId);
            if (goodsMoney <= money) {
                //更新用户余额
                return insertInnerOrder(money, goodsMoney, orderGoodsUserId);
            } else {
                return Result.error("余额不足");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("系统错误：" + e.getMessage());
        }
    }


    public Result insertInnerOrder(double money, double goodsMoney, int orderGoodsUserId) {
        double newMoney = money - goodsMoney;
        int i1 = iCheckUserInfoDao.updateMoneyByID(newMoney, orderGoodsUserId);
        int i = iGoodsInfoDao.updateOrderStatus(orderGoodsUserId);
        double newManagerMoney = goodsMoney + innerOrderDao.selectManagerMoney();
        int i2 = iCheckUserInfoDao.updateMoney(newManagerMoney, "admin");
        if (i > 0 && i1 > 0 && i2 > 0) {
            return Result.success("清空成功");
        } else {
            return Result.error("清空失败");
        }
    }

    public double check(int orderGoodsUserId) {//购物车内所有物品的总金额
        //查看用户购物车,遍历所有的购物车订单的余额
        double goodsMoney = 0;
        ArrayList<OrderInfo> orderInfos = iGoodsInfoDao.selectOrder(orderGoodsUserId);
        for (OrderInfo orderInfo : orderInfos) {
            goodsMoney += orderInfo.getOrderValue();
        }
        return goodsMoney;
    }
}